﻿/*****************************************************************
 *Yuga Technology
 *@author Oplink OMS
 *@copyright all rights reserved (c) zengkang007@gmail.com
 *****************************************************************/
package com.oplink.webems.modules.sys.web;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSONObject;
import com.oplink.webems.common.persistence.Page;
import com.oplink.webems.common.utils.CacheUtils;
import com.oplink.webems.common.utils.UserUtils;
import com.oplink.webems.modules.cfg.services.CfgSiteService;
import com.oplink.webems.modules.sys.dto.TreeDTO;
import com.oplink.webems.modules.sys.entity.CfgValue;
import com.oplink.webems.modules.sys.entity.Config;
import com.oplink.webems.modules.sys.entity.User;
import com.oplink.webems.modules.sys.service.ConfigService;
import com.oplink.webems.modules.sys.service.ShiroDbRealm.ShiroUser;
import com.oplink.webems.modules.sys.utils.DTOParseUtil;

/**
 * Config管理的Controller, 使用Restful风格的Urls:
 * 
 * List page : GET /queue/
 * Create pushlet : GET /queue/pushlet
 * Create page : GET /queue/create
 * Create action : POST /queue/create
 * Update page : GET /queue/update/{id}
 * Update action : POST /queue/update
 * Delete action : GET /queue/delete/{id}
 * 告警Controller
 * 
 * @author Oplink OMS
 * @version 2014-09-03
 */
@Controller
@RequestMapping(value = "sys/config")
public class ConfigController extends BaseController {

	@Autowired
	private ConfigService configService;

	@Autowired
	private ConfigService cfgValueService;

	@Autowired
	private CfgSiteService siteService;

	@RequiresPermissions("modules/sys:config:view")
	@RequestMapping(value = { "list", "" }, method = { RequestMethod.GET, RequestMethod.POST })
	public String list(Config config, HttpServletRequest request, HttpServletResponse response, Model model) {
		config.setSort(-1);
		Page<Config> pages = configService.find(new Page<Config>(request, response), config);
		model.addAttribute("pages", pages);
		model.addAttribute("entity", config);
		return "modules/sys/configList";
	}

	/**
	 * 返回根据catalog分类的树形控件
	 * 
	 * @return
	 */
	@RequestMapping(value = { "listDTO" }, method = { RequestMethod.GET })
	@ResponseBody
	public List<TreeDTO> listDTO() {
		return siteService.getDTOList();
	}

	/**
	 * 返回根据catalog分类的树形控件
	 * 
	 * @return
	 */
	@RequestMapping(value = { "listCfgDTO/{catalog}" }, method = { RequestMethod.GET })
	@ResponseBody
	public List<TreeDTO> listCfgDTO(@PathVariable("catalog") String catalog) {

		List<TreeDTO> listTreeOut = new ArrayList<TreeDTO>();
		List<Map<String, String>> listOut = configService.findCfgValue(UserUtils.getCurrentUserId(), catalog);
		for (Map<String, String> item : listOut) {
			listTreeOut.add(DTOParseUtil.fromMap(item));
		}
		return listTreeOut;
	}

	@RequiresPermissions("modules/sys:config:edit")
	@RequestMapping(value = "update/{id}", method = RequestMethod.GET)
	@ResponseBody
	public Config updateForm(@PathVariable("id") Long id) {
		Config config = configService.getConfig(id);
		config.setUser(null);
		return config;
	}

	@RequestMapping(value = "rstCache", method = RequestMethod.GET)
	@ResponseBody
	public String rstCache() {
		try {
			CacheUtils.clearAll();
			return "0";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "1";
	}

	@RequestMapping(value = "update", method = RequestMethod.POST)
	@ResponseBody
	public String update(@Valid @ModelAttribute("config") Config config, RedirectAttributes redirectAttributes) {
		try {
			User user = new User(getCurrentUserId());
			config.setUser(user);
			// 更新ids
			config.setParentIds(config.getParentId() + "." + config.getId());
			configService.saveConfig(config);
			redirectAttributes.addFlashAttribute("message", "更新任务成功");
			return "1";
		} catch (Exception e) {
			return "0";
		}
	}

	@RequiresPermissions("modules/sys:config:view")
	@RequestMapping(value = "form")
	public String form(Config config, Model model) {
		model.addAttribute("config", config);
		return "modules/sys/configForm";
	}

	@RequiresPermissions("modules/sys:config:edit")
	@RequestMapping(value = "create", method = RequestMethod.GET)
	public String createForm(Model model) {
		model.addAttribute("userId", getCurrentUserId());
		model.addAttribute("action", "create");
		return "modules/sys/config/create";
	}

	@RequestMapping(value = "create", method = RequestMethod.POST)
	@ResponseBody
	public String create(Config config, RedirectAttributes redirectAttributes, Model model) {
		try {
			User user = new User(getCurrentUserId());
			config.setUser(user);
			model.addAttribute("config", config);
			configService.saveConfig(config);
			// 更新ids
			String parentId = (config.getParentId() == null) ? "0" : config.getParentId();
			config.setParentIds(parentId + "." + config.getId());
			configService.saveConfig(config);
			redirectAttributes.addFlashAttribute("message", "创建任务成功");
			return "1";
		} catch (Exception e) {
			e.printStackTrace();
			return "0";
		}
	}

	@RequestMapping(value = "delete/{id}")
	@ResponseBody
	public String delete(@PathVariable("id") String id, RedirectAttributes redirectAttributes) {
		try {
			String ret = "0";
			if (!"".equals(id)) {
				String[] delList = id.split(",");
				for (String idItem : delList) {
					configService.deleteConfig(Long.valueOf(idItem));
				}
				redirectAttributes.addFlashAttribute("message", "删除任务成功");
				ret = "1";
			} else {
				ret = "0";
			}
			return ret;
		} catch (Exception e) {
			return "0";
		}
	}

	/**
	 * 取出Shiro中的当前用户Id.
	 */
	private Long getCurrentUserId() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		return user.id;
	}

	/**
	 * 
	 * @param listConfig
	 * @return
	 */
	@RequestMapping(value = "addList")
	@ResponseBody
	public Map<String, String> addCfgValue(HttpServletRequest request) {
		List<CfgValue> listConfig = new ArrayList<CfgValue>();
		String jsonData = request.getParameter("jsonData");

		JSONObject object = (JSONObject) JSONObject.parse(jsonData);
		String catalog = object.getString("catalog");
		Map<String, String> dataList = (Map<String, String>) object.get("dataList");
		Iterator<String> iter = dataList.keySet().iterator();
		while (iter.hasNext()) {
			CfgValue cfg = new CfgValue();
			cfg.setCatalog(catalog);
			String field = iter.next();
			String value = dataList.get(field);
			cfg.setField(field);
			cfg.setValue(value);
			cfg.setUser(new User(getCurrentUserId()));
			listConfig.add(cfg);
		}
		Map<String, String> outResult = cfgValueService.addConfigValue(getCurrentUserId(), catalog, listConfig);
		if (outResult != null) {
			outResult.put("catalog", catalog);
		}
		return outResult;
	}

	/**
	 * 
	 * @param listConfig
	 * @return
	 */
	@RequestMapping(value = "updateCfg", method = RequestMethod.POST)
	@ResponseBody
	public Boolean updateCfgValue(HttpServletRequest request) {
		List<CfgValue> listConfig = new ArrayList<CfgValue>();
		String jsonData = request.getParameter("jsonData");

		JSONObject object = (JSONObject) JSONObject.parse(jsonData);
		String catalog = object.getString("catalog");
		String formID = object.getString("formID");
		Map<String, String> dataList = (Map<String, String>) object.get("dataList");
		Iterator<String> iter = dataList.keySet().iterator();
		while (iter.hasNext()) {
			CfgValue cfg = new CfgValue();
			cfg.setCatalog(catalog);
			String field = iter.next();
			String value = dataList.get(field);
			cfg.setField(field);
			cfg.setValue(value);
			cfg.setUser(new User(getCurrentUserId()));
			listConfig.add(cfg);
		}
		return cfgValueService.updateConfigValue(formID, getCurrentUserId(), catalog, listConfig);
	}

	@RequestMapping(value = "updateCfg/{fid},{catalog}", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, String> updateForm(@PathVariable("fid") String fid, @PathVariable("catalog") String catalog) {
		return cfgValueService.findForm(fid, getCurrentUserId(), catalog);
	}

	/**
	 * 删除配置值
	 * 
	 * @param listConfig
	 * @return
	 */
	@RequestMapping(value = "delCfg/{catalog}/{fid}")
	@ResponseBody
	public Boolean delCfgValue(@PathVariable("fid") String fid, @PathVariable("catalog") String catalog) {
		return cfgValueService.delConfigValue(fid, getCurrentUserId(), catalog);
	}
}
